<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/avatar.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/avatar.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/avatar.ico?v=6.3.0">


  <link rel="mask-icon" href="/avatar.ico?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.3.0',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="一句精辟的话：字符串相关算法就是用来偷懒的——scy更详细地解释：Manacher、莫队、fft、后缀数组、exkmp等各种算法，本质上都是尽量地利用子信息、残留信息">
<meta name="keywords" content="原创精华,字符串,KMP">
<meta property="og:type" content="article">
<meta property="og:title" content="【OI之路】10字符串-1KMP">
<meta property="og:url" content="http://zory.cf/posts/c111.html">
<meta property="og:site_name" content="Zory的个人博客">
<meta property="og:description" content="一句精辟的话：字符串相关算法就是用来偷懒的——scy更详细地解释：Manacher、莫队、fft、后缀数组、exkmp等各种算法，本质上都是尽量地利用子信息、残留信息">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/0.png">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/1.png">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/2.png">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/7.png">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/8.png">
<meta property="og:image" content="http://zory.cf/images/OI之路/KMP/9.png">
<meta property="og:updated_time" content="2018-08-20T07:26:08.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【OI之路】10字符串-1KMP">
<meta name="twitter:description" content="一句精辟的话：字符串相关算法就是用来偷懒的——scy更详细地解释：Manacher、莫队、fft、后缀数组、exkmp等各种算法，本质上都是尽量地利用子信息、残留信息">
<meta name="twitter:image" content="http://zory.cf/images/OI之路/KMP/0.png">






  <link rel="canonical" href="http://zory.cf/posts/c111.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【OI之路】10字符串-1KMP | Zory的个人博客</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?6c38ba8648d29103b8d122f998787d71";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zory的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">人生即使不能走最短路，仍是连通图</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />历程Archives<span class="badge">354</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类Categories<span class="badge">4</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签Tags<span class="badge">133</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-template">
    <a href="/categories/OI之路" rel="section">
      <i class="menu-item-icon fa fa-fw fa-telegram"></i> <br />OI之路</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-problems">
    <a href="/categories/刷题" rel="section">
      <i class="menu-item-icon fa fa-fw fa-list-alt"></i> <br />刷题Problems</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-friends">
    <a href="/friends/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user-circle"></i> <br />友链Friends</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-english">
    <a href="/English/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-etsy"></i> <br />English知识体系</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-boutique">
    <a href="/tags/原创精华/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-handshake-o"></i> <br />原创精华</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />排行榜Hot</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />找文章强烈建议使用-搜索Search</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="这个搜索超级好用哦！找文章必备！" spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zory.cf/posts/c111.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zory">
      <meta itemprop="description" content="人生即使不能走最短路，仍是连通图">
      <meta itemprop="image" content="http://ouk2t1pgs.bkt.clouddn.com/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zory的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">【OI之路】10字符串-1KMP
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建于：2003-01-22 00:10:01" itemprop="dateCreated datePublished" datetime="2003-01-22T00:10:01+08:00">2003-01-22</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改于：2018-08-20 15:26:08" itemprop="dateModified" datetime="2018-08-20T15:26:08+08:00">2018-08-20</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/OI之路/" itemprop="url" rel="index"><span itemprop="name">OI之路</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/posts/c111.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论：</span> <span class="post-comments-count valine-comment-count" data-xid="/posts/c111.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/posts/c111.html" class="leancloud_visitors" data-flag-title="【OI之路】10字符串-1KMP">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>一句精辟的话：字符串相关算法就是用来偷懒的——scy</strong><br>更详细地解释：Manacher、莫队、fft、后缀数组、exkmp等各种算法，本质上都是尽量地利用子信息、残留信息<br><a id="more"></a></p>
<h2 id="一、说在正文前的小声明"><a href="#一、说在正文前的小声明" class="headerlink" title="一、说在正文前的小声明"></a>一、说在正文前的小声明</h2><p>网络上有关KMP的文章灰常多，本文旨在给初学者一个大致理解，<br>尽量以最简单最直观的方式实现kmp，而不考虑太多有关性能的问题。</p>
<p>参考文献（或者说建议你看看的东西）：<br><a href="http://blog.csdn.net/theflowerofac/article/details/50788104" target="_blank" rel="noopener">1(并不是他原创，但原文找不到了。。)，用了个图片和栗子</a><br><a href="http://www.cnblogs.com/xiaoboCSer/p/4237941.html" target="_blank" rel="noopener">2 栗子比较完整，大家有兴趣可以看看，对本文无用</a><br><a href="http://ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html" target="_blank" rel="noopener">3 阮一峰，挺好的，用了图片和前后缀角度的看法</a><br><a href="http://blog.csdn.net/v_july_v/article/details/7041827#" target="_blank" rel="noopener">4 v_july_v，太强了，堪称完美，建议理解本文后去这里提高，目前我持膜拜状态</a><br><a href="http://www.matrix67.com/blog/archives/115" target="_blank" rel="noopener">5 matrix67，绝对经典</a></p>
<h2 id="二、定义"><a href="#二、定义" class="headerlink" title="二、定义"></a>二、定义</h2><p>Knuth-Morris-Pratt字符串查找算法，简称为”KMP算法”，常用于在一个文本串S(母串)内查找一个模式串P(子串)的出现位置，这个算法由Donald Knuth、Vaughan Pratt、James H.Morris三人于1977年联合发表，故取这3人的姓氏命名此算法。<br>KMP算法的主要作用在于，计算出字符串B是否为字符串A的子串及其系列问题。<br>它比简单的暴力算法更优秀的地方在于，当部分匹配失败时，暴力算法一个个字符向前回溯，KMP则通过预先根据字符串B所计算出的”假如我的下一个字符失配，我的新对应位置”（通常用Next数组表示）。由于此预处理过程只是与字符串B有关，所以很适合处理”某个字符串B验证多个字符串A是否是其母串”一类问题。</p>
<h2 id="三、利用Next数组求解KMP"><a href="#三、利用Next数组求解KMP" class="headerlink" title="三、利用Next数组求解KMP"></a>三、利用Next数组求解KMP</h2><p>Next的性质（你要是想成定义也行）<br>（在实现中，通常把Next用其他更简短的单词表示，本文用p）<br>B[1..p[i]]=B[i-p[i]+1..i]<br>并且要求p[i]最大，从而让移动距离最小，成功可能性更大并且没有漏网之鱼，类似贪心思想</p>
<p>假设现在字符串A[i-1]匹配成功，字符串B[j]匹配成功<br>伪代码：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">j=<span class="number">0</span>;</div><div class="line"><span class="keyword">for</span> i=<span class="number">1</span> to lenA</div><div class="line">&#123;</div><div class="line">    <span class="keyword">while</span>(j&gt;<span class="number">0</span> and a[i]!=b[j+<span class="number">1</span>]) j=p[j];</div><div class="line">    <span class="comment">//将匹配成功的j的p[j]重新尝试对齐i-1</span></div><div class="line">    <span class="comment">//此举意味着失配时，字符串B相对于字符串A向右移动了j-Next[j]位</span></div><div class="line">    <span class="keyword">if</span>(a[i]==b[j+<span class="number">1</span>]) j++;</div><div class="line">    <span class="comment">//此时j成功匹配</span></div><div class="line">    如果(j==lenb) ans++;</div><div class="line">    <span class="comment">//这句话看情况，目前表示统计的答案数+1（如果想搜出来的不重叠就加上j=0）</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="三、Next数组"><a href="#三、Next数组" class="headerlink" title="三、Next数组"></a>三、Next数组</h2><blockquote>
<ul>
<li>对称不是中心对称，而是<strong>中心字符块对称</strong>，比如不是abba，而是abab这种对称</li>
<li>“前缀”指除了最后一个字符以外，一个字符串的<strong>全部</strong>头部组合</li>
<li>“后缀”指除了最前一个字符以外，一个字符串的<strong>全部</strong>尾部组合</li>
</ul>
</blockquote>
<p>那么Next数组究竟怎么求？这也是网络上有关KMP最大的争议。<br>首先，Next数组有几种定义（这也是为何初学者很容易混淆）。<br>不过殊途同归，next本质上是相同的~</p>
<h2 id="四、Next的角度1"><a href="#四、Next的角度1" class="headerlink" title="四、Next的角度1"></a>四、Next的角度1</h2><p>“最大长度值”是”前缀”和”后缀”的最长的共有元素的长度。<br>以”ABCDABD”为例。</p>
<p>(个人认为这个也适合作为性质去记忆而非求法，虽然听老师讲了一遍后开始折服于此)</p>
<table>
<thead>
<tr>
<th style="text-align:center">序号</th>
<th style="text-align:center">1</th>
<th style="text-align:center">2</th>
<th style="text-align:center">3</th>
<th style="text-align:center">4</th>
<th style="text-align:center">5</th>
<th style="text-align:center">6</th>
<th style="text-align:center">7</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">字符</td>
<td style="text-align:center">A</td>
<td style="text-align:center">B</td>
<td style="text-align:center">C</td>
<td style="text-align:center">D</td>
<td style="text-align:center">A</td>
<td style="text-align:center">B</td>
<td style="text-align:center">D</td>
</tr>
<tr>
<td style="text-align:center">最大长度</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">1</td>
<td style="text-align:center">2</td>
<td style="text-align:center">0</td>
</tr>
</tbody>
</table>
<p>“A”的前缀和后缀都为空集，共有元素的长度为0；<br>“AB”的前缀为[A]，后缀为[B]，共有元素的长度为0；<br>“ABC”的前缀为[A,AB]，后缀为[BC,C]，共有元素的长度0；<br>“ABCD”的前缀为[A,AB,ABC]，后缀为[BCD,CD,D]，共有元素的长度为0；<br>“ABCDA”的前缀为[A,AB,ABC,ABCD]，后缀为[BCDA,CDA,DA,A]，共有元素为”A”，长度为1；<br>“ABCDAB”的前缀为[A,AB,ABC,ABCD,ABCDA]，后缀为[BCDAB,CDAB,DAB,AB,B]，共有元素为”AB”，长度为2；<br>“ABCDABD”的前缀为[A,AB,ABC,ABCD,ABCDA,ABCDAB]，<br>后缀为[BCDABD,CDABD,DABD,ABD,BD,D]，共有元素的长度为0。</p>
<p>所以，p[i]可以说是从1到i形成的字符串中的最大长度值。<br>其实与前面说的“s(1,p[i])=s(i-p[i]+1,i)”是一样的</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">2</span>;i&lt;=lenb;i++)<span class="comment">//X2，后缀头不变尾延长</span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">while</span>(j&gt;<span class="number">0</span> and b[j+<span class="number">1</span>]!=b[i]) j=p[j];<span class="comment">//让前缀和后缀同时增长</span></div><div class="line">    <span class="comment">//j是前缀的尾同时也是最大长度值，必然比i小所以其p已经计算出了</span></div><div class="line">	<span class="comment">//失败的时候找更小一点的对称，也就从蓝色转变为红色来延长</span></div><div class="line">    <span class="keyword">if</span>(b[i]==b[j+<span class="number">1</span>]) p[i]=++j; <span class="keyword">else</span> p[i]=<span class="number">0</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>同样的代码，不同的理解方式。</p>
<p>另一个更贴合本理解的代码<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">2</span>;i&lt;=lenb;i++)<span class="comment">//图片中的X2，后缀头不变尾延长</span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">int</span> j=p[i<span class="number">-1</span>];<span class="comment">//图片中的x1-1，因此蓝色相等</span></div><div class="line">    <span class="keyword">while</span>(j&gt;<span class="number">0</span> and sb[i]!=sb[j+<span class="number">1</span>]) j=p[j];</div><div class="line">    <span class="keyword">if</span>(sb[i]==sb[j+<span class="number">1</span>]) p[i]=j+<span class="number">1</span>; <span class="keyword">else</span> p[i]=<span class="number">0</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这两份代码可以结合图片理解，i就是x2，j是x1-1<br><img src="../images/OI之路/KMP/0.png" alt=""></p>
<h2 id="五、Next的角度2"><a href="#五、Next的角度2" class="headerlink" title="五、Next的角度2"></a>五、Next的角度2</h2><p>Next数组相当于“最大长度值”整体向右移动一位，然后初始值赋为-1</p>
<table>
<thead>
<tr>
<th style="text-align:center">序号</th>
<th style="text-align:center">1</th>
<th style="text-align:center">2</th>
<th style="text-align:center">3</th>
<th style="text-align:center">4</th>
<th style="text-align:center">5</th>
<th style="text-align:center">6</th>
<th style="text-align:center">7</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">字符</td>
<td style="text-align:center">A</td>
<td style="text-align:center">B</td>
<td style="text-align:center">C</td>
<td style="text-align:center">D</td>
<td style="text-align:center">A</td>
<td style="text-align:center">B</td>
<td style="text-align:center">D</td>
</tr>
<tr>
<td style="text-align:center">最大长度</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">1</td>
<td style="text-align:center">2</td>
<td style="text-align:center">0</td>
</tr>
<tr>
<td style="text-align:center">Next</td>
<td style="text-align:center">-1</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">1</td>
<td style="text-align:center">2</td>
</tr>
</tbody>
</table>
<p>其实这个角度本质上和上一个一样，只不过这样就能”在j失配时直接对j跳转“而不是”在j+1失配时对j跳转“<br>《最大长度值》字符串B向右移动的位数[已匹配字符位置-失配字符的上一位字符的最大长度值]<br>《Next数组》字符串B向右移动的位数[失配字符的位置-失配字符对应的Next值]<br>上述两个值相等</p>
<h2 id="六、Next的角度3"><a href="#六、Next的角度3" class="headerlink" title="六、Next的角度3"></a>六、Next的角度3</h2><p>用一个长长的字符串来解释</p>
<table>
<thead>
<tr>
<th style="text-align:center">序</th>
<th style="text-align:center">1</th>
<th style="text-align:center">2</th>
<th style="text-align:center">3</th>
<th style="text-align:center">4</th>
<th style="text-align:center">5</th>
<th style="text-align:center">6</th>
<th style="text-align:center">7</th>
<th style="text-align:center">8</th>
<th style="text-align:center">9</th>
<th style="text-align:center">10</th>
<th style="text-align:center">11</th>
<th style="text-align:center">12</th>
<th style="text-align:center">13</th>
<th style="text-align:center">14</th>
<th style="text-align:center">15</th>
<th style="text-align:center">16</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">符</td>
<td style="text-align:center">A</td>
<td style="text-align:center">G</td>
<td style="text-align:center">C</td>
<td style="text-align:center">T</td>
<td style="text-align:center">A</td>
<td style="text-align:center">G</td>
<td style="text-align:center">C</td>
<td style="text-align:center">A</td>
<td style="text-align:center">G</td>
<td style="text-align:center">C</td>
<td style="text-align:center">T</td>
<td style="text-align:center">A</td>
<td style="text-align:center">G</td>
<td style="text-align:center">C</td>
<td style="text-align:center">T</td>
<td style="text-align:center">G</td>
</tr>
<tr>
<td style="text-align:center">Ne</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">0</td>
<td style="text-align:center">1</td>
<td style="text-align:center">2</td>
<td style="text-align:center">3</td>
<td style="text-align:center">1</td>
<td style="text-align:center">2</td>
<td style="text-align:center">3</td>
<td style="text-align:center">4</td>
<td style="text-align:center">5</td>
<td style="text-align:center">6</td>
<td style="text-align:center">7</td>
<td style="text-align:center">4</td>
<td style="text-align:center">0</td>
</tr>
</tbody>
</table>
<p>假设当前字符位置i，子串位置j<br>(1)递推比较<br>把i与j+1进行比较，如果相等，直接继承为上个Next再+1，因为对称程度增加了。<br>如果不相等，跳到(2)，很好理解</p>
<p>(2)回头来找对称性<br><img src="../images/OI之路/KMP/1.png" alt=""></p>
<ul>
<li>t如果要存在对称性，那么对称程度肯定比前面这个c的对称程度小。要找更小的对称，必然在对称内部还存在子对称，而且这个t必须紧接着在子对称之后。</li>
<li>可以通过循环j=Next[j]不断找更小对称性<br><img src="../images/OI之路/KMP/2.png" alt=""><br>个人感觉类似自己匹配自己</li>
</ul>
<h2 id="七、代码"><a href="#七、代码" class="headerlink" title="七、代码"></a>七、代码</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//*******************定义*******************</span></div><div class="line"><span class="keyword">int</span> p[<span class="number">11100</span>],lenb;<span class="keyword">char</span> b[<span class="number">11000</span>];</div><div class="line"><span class="comment">//*******************实现*******************</span></div><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">calcb</span><span class="params">(<span class="keyword">void</span>)</span></div><div class="line"></span>&#123;</div><div class="line">    lenb=<span class="built_in">strlen</span>(b+<span class="number">1</span>);</div><div class="line">    <span class="keyword">int</span> j=<span class="number">0</span>;p[<span class="number">1</span>]=<span class="number">0</span>;</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">2</span>;i&lt;=lenb;i++)</div><div class="line">    &#123;</div><div class="line">        <span class="keyword">while</span>(j&gt;<span class="number">0</span> and b[j+<span class="number">1</span>!=b[i]]) j=p[j];</div><div class="line">        <span class="keyword">if</span>(b[i]==b[j+<span class="number">1</span>]) p[i]=++j;</div><div class="line">        <span class="keyword">else</span> p[i]=<span class="number">0</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">int</span> <span class="title">KMP</span><span class="params">(<span class="keyword">char</span> a[])</span></div><div class="line"></span>&#123;</div><div class="line">    <span class="keyword">int</span> lena=<span class="built_in">strlen</span>(a+<span class="number">1</span>);</div><div class="line">    <span class="keyword">int</span> j=<span class="number">0</span>;<span class="keyword">int</span> ans=<span class="number">0</span>;</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=lena;i++)</div><div class="line">    &#123;</div><div class="line">        <span class="keyword">while</span>(j&gt;<span class="number">0</span> and a[i]!=b[j+<span class="number">1</span>]) j=p[j];</div><div class="line">        <span class="keyword">if</span>(a[i]==b[j+<span class="number">1</span>]) j++;</div><div class="line">        <span class="keyword">if</span>(j==lenb) ans++,j=<span class="number">0</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> ans;</div><div class="line">&#125;</div><div class="line"><span class="comment">//*******************主函数*******************</span></div><div class="line"><span class="keyword">char</span> a[<span class="number">11000</span>];</div><div class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span></div><div class="line"></span>&#123;</div><div class="line">    <span class="keyword">int</span> n;<span class="built_in">scanf</span>(<span class="string">"%d"</span>,&amp;n);</div><div class="line">    <span class="keyword">while</span>(n--)</div><div class="line">    &#123;</div><div class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>,b+<span class="number">1</span>);</div><div class="line">        calcb();</div><div class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>,a+<span class="number">1</span>);</div><div class="line">        <span class="built_in">printf</span>(<span class="string">"%d\n"</span>,KMP(a));</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>检验数据：</strong><br><strong>Input</strong><br>alkdfj<br>haljhdgelqigljafiehiqhroug<br>sgs<br>sgsgijosgsjeswsgjjiigj</p>
<p><strong>Output</strong><br>0<br>2</p>
<h2 id="八、练习"><a href="#八、练习" class="headerlink" title="八、练习"></a>八、练习</h2><p><a href="9bc9.html">陶陶的名字</a><br>（可以重叠的最小覆盖）</p>
<h2 id="九、kmp与最小覆盖"><a href="#九、kmp与最小覆盖" class="headerlink" title="九、kmp与最小覆盖"></a>九、kmp与最小覆盖</h2><p>参考文献：<a href="https://blog.csdn.net/fjsd155/article/details/6866991" target="_blank" rel="noopener">FarmerJohn</a></p>
<p>定义：<br>对于一个字符串，一个长度最小的满足<br>【复制自己多次（不重叠，与陶陶的名字不同）后可以覆盖原串】的子串</p>
<p>结论：<br>长度=n-next[n]</p>
<p>证明：<br>先证明它是覆盖子串<br>①next[n]&lt;=n-next[n]<br><img src="../images/OI之路/KMP/7.png" alt=""><br>显而易见覆盖</p>
<p>②next[n]&gt;n-next[n]<br><img src="../images/OI之路/KMP/8.png" alt=""></p>
<p>然后它也是最小的<br>这里用反证法，假设存在一个比n-next[n]更小的C，然后截取掉<br><img src="../images/OI之路/KMP/9.png" alt=""><br>这样的话，黄色部分比next[n]更长，不满足next[n]是最长这个定义</p>
<p>Q.E.D.</p>

      
    </div>

    
    
    

    
      <div class="post-tags">
        
          <a href="/tags/原创精华/" rel="tag"># 原创精华</a>
        
          <a href="/tags/字符串/" rel="tag"># 字符串</a>
        
          <a href="/tags/KMP/" rel="tag"># KMP</a>
        
      </div>
    

    
      

  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/80c8.html" rel="bookmark">【置顶】套路集锦</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/3834.html" rel="bookmark">【置顶】码风与卡常技巧</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/7748.html" rel="bookmark">【OI之路】02数论算法-1公约数公倍数与欧几里得</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/f6c6.html" rel="bookmark">【OI之路】09经典问题-3哈夫曼树</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/d81d.html" rel="bookmark">【OI之路】11更高级数论-3莫比乌斯反演</a></div>
      
    </li>
  
  </ul>


    

	
		<div>
				<p id="div-border-left-purple">
			   <b>本文基于<a target="_blank" title="Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)" href="http://creativecommons.org/licenses/by-sa/4.0/deed.zh"> 知识共享署名-相同方式共享 4.0 </a>国际许可协议发布</b><br/>
				<span>
				<b>本文地址：</b><a href="/posts/c111.html" title="【OI之路】10字符串-1KMP">http://zory.cf/posts/c111.html</a><br/><b>转载请注明出处，谢谢！</b>
				</span>
				</p>
		</div>
    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>哪怕是一杯奶茶，也将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Zory 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/f6c6.html" rel="next" title="【OI之路】09经典问题-3哈夫曼树">
                <i class="fa fa-chevron-left"></i> 【OI之路】09经典问题-3哈夫曼树
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/1c35.html" rel="prev" title="【OI之路】10字符串-2Manacher">
                【OI之路】10字符串-2Manacher <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://ouk2t1pgs.bkt.clouddn.com/avatar.jpg"
                alt="Zory" />
            
              <p class="site-author-name" itemprop="name">Zory</p>
              <p class="site-description motion-element" itemprop="description">人生即使不能走最短路，仍是连通图</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">354</span>
                    <span class="site-state-item-name">文章</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">133</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/Zory123" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1134430323@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

<script type="text/javascript" src="https://api.lwl12.com/hitokoto/main/get?encode=js&charset=utf-8"></script>
<div id="lwlhitokoto">
    <script>
        lwlhitokoto()
    </script>
</div>

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、说在正文前的小声明"><span class="nav-text">一、说在正文前的小声明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、定义"><span class="nav-text">二、定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、利用Next数组求解KMP"><span class="nav-text">三、利用Next数组求解KMP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、Next数组"><span class="nav-text">三、Next数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、Next的角度1"><span class="nav-text">四、Next的角度1</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、Next的角度2"><span class="nav-text">五、Next的角度2</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、Next的角度3"><span class="nav-text">六、Next的角度3</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、代码"><span class="nav-text">七、代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#八、练习"><span class="nav-text">八、练习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#九、kmp与最小覆盖"><span class="nav-text">九、kmp与最小覆盖</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zory</span>

  

  
</div>


  









  <div class="footer-custom">Hosted by <a target="_blank" rel="external nofollow" href="https://pages.coding.me"><b>Coding Pages</b></a></div>


        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: true,
        appId: 'zMDFLwV3WMlWrOYhJ7tOad3M-gzGzoHsz',
        appKey: 'cJDLxDoNgzq0JJUWQFmpCRdw',
        placeholder: '对这篇文章有什么看法？大胆地说出来吧',
        avatar:'wavatar',
        guest_info:guest,
        pageSize:'20' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('2');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("zMDFLwV3WMlWrOYhJ7tOad3M-gzGzoHsz", "cJDLxDoNgzq0JJUWQFmpCRdw");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
            counter.save(null, {
              success: function(counter) {
                
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.get('time'));
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var newcounter = new Counter();
              /* Set ACL */
              var acl = new AV.ACL();
              acl.setPublicReadAccess(true);
              acl.setPublicWriteAccess(true);
              newcounter.setACL(acl);
              /* End Set ACL */
              newcounter.set("title", title);
              newcounter.set("url", url);
              newcounter.set("time", 1);
              newcounter.save(null, {
                success: function(newcounter) {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
                },
                error: function(newcounter, error) {
                  console.log('Failed to create');
                }
              });
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook,GooglePlus,Evernote,Vkontakte";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
  
  <script src="/lib/pangu/dist/pangu.min.js?v=3.3"></script>
  <script type="text/javascript">pangu.spacingPage();</script>


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.3.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.3.0"></script>


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Copied')
          else $(this).text('Copy failed')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>


</body>
</html>
